'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
  // 注册用户
  async createUser () {
    const { ctx } = this;
    const { account, password } = ctx.request.body;
    const payload = this.ctx.request.body;
    var data;
    if (!account || !password) {
      ctx.body = {
        code: 500,
        msg: '用户名密码不能为空',
        data: null
      };
      return;
    }
    let message = '';
    // console.log(typeof account);
    const res = await ctx.app.mysql.query(
      `select * from user where account='${account}'`
    );
    // console.log(res);
    if (res.length !== 0) {
      message = '用户已存在';
      ctx.body = {
        code: 500,
        message,
        data
      };
    } else {
      const insertresult = await ctx.service.user.createUser(payload);
      if (!insertresult) {
        message = '注册失败';
        ctx.body = {
          code: 500,
          message,
          data
        };
      } else {
        message = '注册成功';
        data = insertresult;
        ctx.body = {
          code: 200,
          message,
          data
        };
      }
    }

  }
  // 登陆
  async login () {
    const { ctx } = this;
    // post请求传来的参数
    const { account, password } = ctx.request.body;
    let message = '',
      data = {};
    // 判断数据库里面是否存在该用户
    const user = JSON.parse(JSON.stringify(await ctx.app.mysql.query(`select * from user where account='${account}'`)));
    if (user.length == 0) {
      message = '用户不存在';
      ctx.body = {
        code: 500,
        message,
        data,
      };
    } else if (password !== user[0].password) {
      message = '密码错误';
      ctx.body = {
        code: 500,
        message,
        data,
      };
    } else {
      message = '登录成功';
      const token = ctx.app.jwt.sign({ account: user[0].account }, this.app.config.jwt.secret, { expiresIn: "24h" });//h、m、s分别对应时分秒
      data = { id: user[0].id, token: token, userInfo: user[0] };
      ctx.body = {
        code: 200,
        message,
        data,
      };
    }

  }
}

module.exports = UserController;
